using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Cinemachine;
using Cysharp.Threading.Tasks;
using MyFrame.Single;
using Plugin.Tool;
using UnityEngine;

public class CameraMgr : SingletonMonoGlobal<CameraMgr>
{
    // 默认的屏幕震动源
    private CinemachineImpulseSource screenShakeSource;

    public float shakeMultiplier = 0.1f;

    public float slowMotionTimeScale = 0.5f; // 慢动作时的时间缩放值


    void Awake()
    {
        screenShakeSource = GetComponent<CinemachineImpulseSource>();
    }

    /// <summary>
    /// 启动震屏效果
    /// </summary>
    /// <param name="shakePower"></param>
    /// <param name="impulseSource">触发源，暂时都用默认的</param>
    public void TriggerScreenShake(Vector2 shakePower, CinemachineImpulseSource impulseSource = null)
    {
        var player = GameMgr.Instance.player;

        // 设置震动的力度，结合玩家的朝向
        if (impulseSource != null)
            impulseSource.GenerateImpulse(new Vector3(shakePower.x, shakePower.y, 0) * shakeMultiplier);
        else
            screenShakeSource.GenerateImpulse(new Vector3(shakePower.x, shakePower.y, 0) * shakeMultiplier);
    }

    // 启动顿帧效果
    private readonly SemaphoreSlim _timeFreezeLock = new SemaphoreSlim(1, 1); // 初始化异步锁

    public void TriggerTimeFreeze(float duration)
    {
        FreezeTime(duration).Forget(); // 直接调用异步方法
    }

    private async UniTask FreezeTime(float duration)
    {
        await _timeFreezeLock.WaitAsync(); // 异步等待获取锁

        try
        {
            float originalTimeScale = Time.timeScale; // 保存当前时间缩放
            if (Time.timeScale == 0)
            {
                Debug.LogError("震动锁失败");
            }
            Time.timeScale = 0f; // 设置时间缩放为0，暂停时间

            await UniTask.Delay((int)(duration * 1000), ignoreTimeScale: true); // 等待指定时长，忽略时间缩放

            Time.timeScale = originalTimeScale; // 恢复原始时间缩放
        }
        finally
        {
            _timeFreezeLock.Release(); // 释放锁
        }
    }

    //局部顿帧  
    public void TriggerLocalTimeFreeze(Animator animator, float duration){
        animator.speed = 0f;
        // ZTimer.SetInterval(0.01f, () => {
        //     Debug.Log(animator.GetAnimatorTransitionInfo(0).normalizedTime);
        // });
        ZTimer.SetTimeout(duration, () => animator.speed = 1f);
    }



}
